/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { forwardRef, useState, useCallback, useEffect } from "react";
import { Input, Select } from "antd";
import { spliceURL } from "@/utils/patterns";

const { Option } = Select;

const SelectBefore = ({ onChange, urlType = "https://" }) => (
  <Select onChange={onChange} value={urlType} style={{ width: 90 }}>
    <Option value="https://">https://</Option>
    <Option value="http://">http://</Option>
  </Select>
);

const InputWithHttps = forwardRef((props, ref) => {
  const { value, onChange, showAddBefore = true, ...rest } = props;

  const [urlType, setUrlType] = useState("https://");
  const [inputVal, setInputVal] = useState(value);

  const formatValue = useCallback(
    (val, protocol) => {
      const urlBody = spliceURL(val, "body");

      const realValue = showAddBefore ? (urlBody ? `${protocol}${urlBody}` : undefined) : val;
      setInputVal(urlBody);
      onChange && onChange(realValue);
    },
    [onChange, showAddBefore]
  );

  const onInputChange = useCallback(
    e => {
      const inputValue = e.target.value;
      formatValue(inputValue, urlType);
    },
    [formatValue, urlType]
  );

  const onSelect = useCallback(
    values => {
      formatValue(inputVal, values);
      setUrlType(values);
    },
    [inputVal, formatValue]
  );

  useEffect(
    () => {
      const protocol = spliceURL(value, "protocol");
      const urlBody = spliceURL(value, "body");
      setUrlType(protocol || "https://");
      setInputVal(urlBody || "");
    },
    [value]
  );

  return (
    <Input
      value={inputVal}
      onChange={onInputChange}
      {...rest}
      addonBefore={showAddBefore ? <SelectBefore onChange={onSelect} urlType={urlType} /> : null}
    />
  );
});

export default InputWithHttps;
